package com.xms.schema.service.optionset;

import com.xms.core.exception.XmsException;
import com.xms.datacore.service.CreaterService;
import com.xms.schema.entity.OptionSet;
import com.xms.schema.entity.OptionSetDetail;
import com.xms.utils.CollectionUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.SQLException;
import java.util.Collection;
import java.util.List;

/**
 * <p>
 * OptionsetCreaterService
 * </p>
 *
 * @author migo
 * @since 2021/9/3
 */
@CacheConfig(cacheNames = "schema.optionset", keyGenerator = "CacheKeyGenerator")
@Service
public class OptionSetCreaterService extends CreaterService<OptionSet> implements IOptionSetCreaterService {
    private IOptionSetDetailCreaterService _optionSetDetailCreaterService;
    @Autowired
    public void OptionsetCreaterService(IOptionSetDetailCreaterService optionSetDetailCreaterService) {
        _optionSetDetailCreaterService = optionSetDetailCreaterService;
    }

    @CacheEvict(allEntries = true, condition = "#result == true")
    @Transactional(rollbackFor=Exception.class)
    @Override
    public boolean create(OptionSet entity) throws XmsException, SQLException {
        super.save(entity);
        if(CollectionUtil.notEmpty(entity.getItems())) {
            _optionSetDetailCreaterService.createMany(entity.getItems());
        }
        return true;
    }

    @CacheEvict(allEntries = true, condition = "#result == true")
    @Transactional(rollbackFor=Exception.class)
    @Override
    public boolean create(OptionSet entity, List<OptionSetDetail> items) throws XmsException, SQLException {
        entity.setItems(items);
        return this.create(entity);
    }

    @CacheEvict(allEntries = true, condition = "#result == true")
    @Transactional(rollbackFor=Exception.class)
    @Override
    public boolean createMany(Collection<OptionSet> entityList) throws SQLException, XmsException {
        for (OptionSet entity : entityList){
            this.create(entity);
        }
        return true;
    }
}
